<template>
  <div class="check">
    <div class="container">
      <ul class="cartProcess">
        <li>1.购物车</li>
        <li>2.填写订单</li>
        <li>3.成功提交</li>
      </ul>

      <div class="clear"></div>

      <!-- 填写收货地址 -->
      <div class="address">
        <p class="title">收货地址</p>

        <!-- 填写收货信息 -->
        <el-form
          :model="ruleForm3"
          status-icon
          :rules="rules3"
          ref="ruleForm3"
          label-width="0"
          class="demo-ruleForm"
          v-show="!adrShow"
        >
          <!-- 收货人 -->
          <el-form-item prop="receiver">
            <el-input
              v-model="ruleForm3.receiver"
              auto-complete="off"
              placeholder="收货人"
            ></el-input>
          </el-form-item>

          <!-- 手机号 -->
          <el-form-item prop="tel">
            <el-input
              v-model="ruleForm3.tel"
              auto-complete="off"
              placeholder="手机号码"
            ></el-input>
          </el-form-item>

          <!-- 地区选择 -->
          <!-- <div class="address">
                        <v-distpicker
                            :province="province"
                            :city="city"
                            :area="area"
                            @selected="onSelected"
                        >
                        </v-distpicker>
                    </div> -->

          <!-- 详细地址 -->
          <el-form-item prop="address">
            <el-input
              v-model="ruleForm3.address"
              auto-complete="off"
              placeholder="详细地址"
            ></el-input>
          </el-form-item>

          <!-- 保存按钮 -->
          <el-form-item class="saveBtn">
            <el-button
              type="primary"
              @click="submitForm('ruleForm3')"
              style="width: 100%"
              >保存并使用</el-button
            >
          </el-form-item>
        </el-form>

        <!-- 收货信息展示 -->
        <ul class="addressInfo" v-show="adrShow">
          <li
            class="addressBox"
            v-for="(item, index) in addList"
            :key="item.id"
            :class="{ adrActive: activeIndex == index }"
            @click="adrChecked(index, item.id)"
          >
            <div class="content">
              <p>{{ item.name }}</p>
              <p>{{ item.phone }}</p>
              <p>{{ item.area_name }}{{ item.desc }}</p>
              <i class="el-icon-edit" @click="editFn(item.id)"></i>
              <i class="el-icon-delete" @click="deleteFn(item.id)"></i>
            </div>
          </li>
          <div class="newAddress" @click="maskShowFn">
            <div class="content">
              <i class="el-icon-plus"></i>
              <p>使用新地址</p>
            </div>
          </div>
        </ul>
      </div>

      <div class="clear"></div>

      <!-- 配送方式 -->
      <div class="ship">
        <p class="title">配送方式</p>
        <div class="postage"><span>默认：普通快递 运费 ¥0</span></div>
      </div>

      <!-- 订单概览 -->
      <div class="order">
        <p class="title">订单概览</p>
        <div class="orderBox">
          <ul v-for="item in cartList" :key="item.id">
            <li>
              <div class="proImg">
                <img :src="item.s_good.s_goods_photos[0].path" alt="" />
              </div>
              <div class="proName">
                <p>{{ item.s_good.name }}</p>
              </div>
              <div class="proPrice">
                <p>¥{{ item.s_good.price }}</p>
              </div>
              <div class="proCount">
                <p>数量：{{ item.num }}</p>
              </div>
              <div class="proTotal">
                <p>¥{{ item.num * item.s_good.price }}</p>
              </div>
            </li>
          </ul>
        </div>
        <div class="fee">
          <p>
            商品总价：<span>￥{{ goodsTotal }}</span>
          </p>
          <p class="feePostage">运费：<span>￥0.00</span></p>
        </div>
        <p class="payable">
          应付金额：<span>￥{{ goodsTotal }}</span>
        </p>
      </div>

      <!-- 按钮 -->
      <div class="payBtn">
        <div class="backCart">
          <router-link to="/shopping"
            ><i class="el-icon-shopping-cart-2"></i>返回购物车</router-link
          >
        </div>
        <div class="toPay">
          <a @click="gotoPay">提交订单，去支付</a>
        </div>
      </div>

      <div class="clear"></div>
    </div>

    <!-- 新增地址遮罩层 -->
    <div class="adrMask" v-show="maskStatus">
      <div class="adrmask-window">
        <div class="content">
          <div class="title">
            <p>{{ adrMaskTitle }}</p>
            <i class="el-icon-close" @click="maskHideFn"></i>
          </div>

          <el-form
            :model="ruleForm3"
            status-icon
            :rules="rules3"
            ref="ruleForm3"
            label-width="0"
            class="demo-ruleForm"
          >
            <!-- 收货人 -->
            <el-form-item prop="receiver">
              <el-input
                v-model="ruleForm3.receiver"
                auto-complete="off"
                placeholder="收货人"
              ></el-input>
            </el-form-item>

            <!-- 手机号 -->
            <el-form-item prop="tel">
              <el-input
                v-model="ruleForm3.tel"
                auto-complete="off"
                placeholder="手机号码"
              ></el-input>
            </el-form-item>

            <!-- 地区选择 -->
            <!-- <div class="address">
                        <v-distpicker
                            :province="province"
                            :city="city"
                            :area="area"
                            @selected="onSelected"
                        >
                        </v-distpicker>
                    </div> -->

            <!-- 详细地址 -->
            <el-form-item prop="address">
              <el-input
                v-model="ruleForm3.address"
                auto-complete="off"
                placeholder="详细地址"
              ></el-input>
            </el-form-item>

            <div class="buttomBtn">
              <!-- 取消按钮 -->
              <div class="cancelBtn" @click="maskHideFn">
                <p>取消</p>
              </div>
              <!-- 保存按钮 -->
              <el-form-item class="saveBtn" v-show="btnStatus">
                <el-button type="primary" @click="submitForm('ruleForm3')"
                  >保存并使用</el-button
                >
              </el-form-item>

              <!-- 编辑按钮 -->
              <el-form-item class="editBtn" v-show="!btnStatus">
                <el-button type="primary" @click="editForm('ruleForm3', id)"
                  >编辑并使用</el-button
                >
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import VDistpicker from "v-distpicker";
import { goAddress } from "../../api/testApi/address";

import axios from "axios";

export default {
  // components: { VDistpicker },

  created() {
    // 接收cart页传递来的勾选商品
    this.cartList = JSON.parse(this.$route.query.str);
    console.log(this.cartList);

    // 获取已添加地址列表
    axios({
      method: "GET",
      url: "http://shop.bluej.cn/api/address",
      headers: {
        "x-token": this.$store.state.token,
      },
    })
      .then((res) => {
        this.addList = res.data.result;
        console.log(this.addList);
        if (this.addList.length) {
          this.adrShow = !this.adrShow;
          // 默认要提交的地址id为第一个
          this.chooseAdrId = this.addList[0].id;
        }
      })
      .then((err) => {});
  },
  computed: {
    // 选中之后的商品总价
    goodsTotal() {
      if (this.cartList.length) {
        // 累加
        return this.cartList.reduce((total, currentItem) => {
          return (total += currentItem.num * currentItem.s_good.price);
        }, 0);
      } else {
        return 0;
      }
    },
  },
  data() {
    // 验证用户名是否合法
    let checkReceiver = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    // 验证手机号是否合法
    let checkTel = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号码"));
      } else if (!this.checkMobile(value)) {
        callback(new Error("手机号码不合法"));
      } else {
        callback();
      }
    };
    return {
      ruleForm3: {
        receiver: "",
        tel: "",
        address: "",
      },
      rules3: {
        receiver: [{ validator: checkReceiver, trigger: "change" }],
        tel: [{ validator: checkTel, trigger: "change" }],
      },
      // 获取的购物车详情列表
      cartList: [],
      // 已添加地址的详细列表
      addList: [],
      // 添加地址的遮罩层状态
      maskStatus: false,
      // 添加地址的遮罩层标题
      adrMaskTitle: "",
      // 默认已有地址的状态
      adrShow: false,
      // 通过btnStatus切换地址的保存与编辑按钮
      btnStatus: true,
      // 要编辑的地址id
      editId: "",
      // 判断选中地址的样式
      activeIndex: 0,
      // 选中将要提交的地址id
      chooseAdrId: 0,
      // 选中将要提交的商品信息
      chooseGoods: [],
    };
  },
  methods: {
    // onSelected(data) {
    //     this.province = data.province.value;
    //     this.city = data.city.value;
    //     this.area = data.area.value;
    //     this.ruleForm.province = this.province;
    //     this.ruleForm.city = this.city;
    //     this.ruleForm.area = this.area;
    // },
    // 验证手机号规范
    checkMobile(str) {
      let re = /^1\d{10}$/;
      if (re.test(str)) {
        return true;
      } else {
        return false;
      }
    },
    // 保存地址信息
    async submitForm() {
      // 不会用地区选择器，故把地区写死
      let addressData = {
        name: this.ruleForm3.receiver,
        phone: this.ruleForm3.tel,
        area: "2,52,501",
        area_name: "北京省市辖区西城区",
        desc: this.ruleForm3.address,
      };
      let token = sessionStorage.getItem("token");
      console.log(token);
      let res = await goAddress(addressData, token);
      console.log(res);
      if (res.status == 200) {
        alert("地址保存成功");
        this.maskStatus = false;
        this.$router.go(0);
      } else {
        alert("保存失败，请检查您填写的信息");
      }
    },
    // 删除地址信息
    deleteFn(id) {
      axios({
        method: "DELETE",
        url: `http://shop.bluej.cn/api/address/${id}`,
        headers: {
          "x-token": this.$store.state.token,
        },
      })
        .then((res) => {
          // 删除刷新本页面
          this.$router.go(0);
        })
        .then((err) => {
          console.log(err);
        });
    },

    // 更新地址信息
    editFn(id) {
      this.maskStatus = true;
      this.adrMaskTitle = "编辑地址";
      this.btnStatus = false;
      // 保存要编辑的地址id
      this.editId = Number(id);
    },
    editForm() {
      axios({
        method: "PUT",
        url: `http://shop.bluej.cn/api/address/${this.editId}`,
        data: {
          name: this.ruleForm3.receiver,
          phone: this.ruleForm3.tel,
          area: "2,52,501",
          area_name: "北京省市辖区西城区",
          desc: this.ruleForm3.address,
        },
        headers: {
          "x-token": this.$store.state.token,
        },
      })
        .then((res) => {
          // 删除刷新本页面
          this.$router.go(0);
        })
        .then((err) => {});
    },
    maskShowFn() {
      this.maskStatus = true;
      this.adrMaskTitle = "添加地址";
    },
    maskHideFn() {
      this.maskStatus = false;
    },
    adrChecked(index, id) {
      this.activeIndex = index;
      this.chooseAdrId = id;
      console.log(this.chooseAdrId);
      console.log(this.cartList);
    },
    gotoPay() {
      // 将商品信息传参给pay页
      let str = JSON.stringify(this.cartList);
      this.$router.push({
        path: "/shopping/pay",
        query: {
          cartList: str,
          adrId: this.chooseAdrId,
          goodsTotal: this.goodsTotal,
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
// 地址选中样式
.adrActive {
  background-color: #f2f9ff !important;
  border: 1px solid #0096ff !important;
}
.check {
  width: 100%;
  min-width: 1200px;
  .container {
    width: 1200px;
    margin: 0 auto;
    .clear {
      clear: both;
    }

    .title {
      font-size: 18px;
      color: #333;
      font-weight: 700;
      text-align: left;
    }

    .cartProcess {
      li {
        display: flex;
        justify-content: center;
        align-items: center;
        float: left;
        width: 400px;
        height: 60px;
        border-bottom: 1px solid #e6e6e6;
        color: #333;
        font-size: 18px;
        &:nth-child(2) {
          color: skyblue;
          border-color: skyblue;
        }
      }
    }

    .address {
      width: 600px;
      margin-top: 48px;
      text-align: left;

      .demo-ruleForm {
        position: relative;
        ::v-deep .el-form-item {
          width: 100%;
          margin: 24px auto 0;
        }
        ::v-deep .el-input__inner {
          font-size: 14px;
          color: #333;
          line-height: 20px;
          border: none;
          padding-bottom: 4px;
          border-radius: 0;
          width: 100%;
          border-bottom: 1px solid rgb(204, 204, 204);
          &:focus {
            outline: medium;
          }
        }
        .saveBtn {
          width: 160px;
          margin-top: 24px;
          background-color: #0096ff;
          border-radius: 2px;
          cursor: pointer;
          font-size: 16px;
          color: #fff;
          line-height: 48px;
          float: left;
          // position: absolute;
          // left: 0;
        }
      }

      .addressInfo {
        width: 980px;
        .addressBox {
          background-color: transparent;
          border: 1px solid #ccc;
          margin-right: 24px;
          margin-top: 24px;
          box-sizing: border-box;
          width: 288px;
          height: 232px;
          border-radius: 2px;
          float: left;
          position: relative;
          cursor: pointer;
          .content {
            width: 240px;
            margin: 20px 0 0 24px;
          }
          p {
            font-size: 14px;
            color: #333;
            line-height: 20px;
            margin-bottom: 12px;
          }
          i {
            width: 24px;
            height: 24px;
            position: absolute;
            top: 192px;
            left: 200px;
            cursor: pointer;
            &:hover {
              color: #0096ff;
            }
            &:last-child {
              left: 240px;
            }
          }
        }
        .newAddress {
          background-color: transparent;
          border: 1px solid #ccc;
          margin-right: 24px;
          margin-top: 24px;
          box-sizing: border-box;
          width: 288px;
          height: 232px;
          border-radius: 2px;
          float: left;
          position: relative;
          cursor: pointer;
          .content {
            width: 70px;
            height: 70px;
            margin: 88px auto;
            text-align: center;
            i {
              font-size: 30px;
              display: block;
            }
            p {
              font-size: 14px;
              color: #333;
              line-height: 20px;
              margin-top: 12px;
            }
          }
        }
      }
    }

    .ship {
      width: 600px;
      margin-top: 72px;
      .postage {
        width: 240px;
        height: 48px;
        margin: 24px 0;
        background-color: #f2f9ff;
        border: 1px solid #0096ff;
        border-radius: 2px;
        span {
          font-size: 14px;
          color: #333;
          text-align: center;
          line-height: 48px;
        }
      }
    }

    .order {
      width: 1200px;
      margin-top: 72px;
      .orderBox {
        margin-top: 24px;
        ul {
          border-top: 1px solid #e6e6e6;
          li {
            width: 100%;
            height: 120px;
            box-sizing: border-box;
            border-bottom: 1px solid #e6e6e6;
            .proImg {
              width: 136px;
              img {
                width: 80px;
                height: 80px;
                margin: 20px 0 0 16px;
              }
            }
            .proImg,
            .proName,
            .proPrice,
            .proCount,
            .proTotal {
              width: 210px;
              height: 120px;
              float: left;
              p {
                font-size: 14px;
                color: #333;
                line-height: 120px;
                text-align: left;
              }
            }
            .proName {
              width: 500px;
            }
            .proCount {
              width: 150px;
            }
            .proTotal {
              width: 130px;
              p {
                color: #ff3232;
              }
            }
          }
        }
      }
      .fee {
        width: 100%;
        height: 72px;
        margin-top: 20px;
        border-bottom: 1px solid #e6e6e6;
        p {
          font-size: 14px;
          color: #666;
          line-height: 20px;
          float: right;
          span {
            color: #ff3232;
          }
        }
        .feePostage {
          clear: both;
          margin-top: 12px;
        }
      }
      .payable {
        margin-top: 20px;
        font-size: 18px;
        color: #666;
        text-align: right;
        span {
          color: #ff3232;
        }
      }
    }

    .payBtn {
      display: flex;
      justify-content: space-between;
      align-items: center;
      float: right;
      width: 336px;
      height: 48px;
      margin: 48px 0 60px;
      .backCart,
      .toPay {
        border: 1px solid #ff3232;
        margin-left: 16px;
        border-radius: 2px;
        width: 160px;
        height: 48px;
        line-height: 48px;
        text-align: center;
        cursor: pointer;
        font-size: 16px;
        display: inline-block;
      }
      .backCart {
        a {
          color: #ff3232;
        }
      }
      .toPay {
        background: #ff3232;
        a {
          color: #fff;
        }
      }
    }
  }
  .adrMask {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.2);
    display: flex;
    .adrmask-window {
      margin: auto;
      background-color: #fff;
      border-radius: 2px;
      width: 640px;
      position: relative;
      .content {
        width: 600px;
        margin: 20px auto;
        .title {
          font-size: 18px;
          color: #333;
          font-weight: 700;
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 45px;
          i {
            cursor: pointer;
          }
        }
        .demo-ruleForm {
          position: relative;
          ::v-deep .el-form-item {
            width: 100%;
          }
          ::v-deep .el-input__inner {
            font-size: 14px;
            color: #333;
            line-height: 20px;
            border: none;
            padding-bottom: 4px;
            border-radius: 0;
            width: 100%;
            border-bottom: 1px solid rgb(204, 204, 204);
            &:focus {
              outline: medium;
            }
          }
          .buttomBtn {
            display: flex;
            width: 380px;
            justify-content: space-between;
            align-items: center;
            margin: 0 auto;
            .cancelBtn {
              color: #0096ff;
              line-height: 48px;
              border: 1px solid #0096ff;
              p {
                text-align: center;
              }
            }
            .cancelBtn,
            ::v-deep .el-button {
              width: 160px;
              height: 48px;
              margin-top: 24px;
              border-radius: 2px;
              cursor: pointer;
              font-size: 16px;
            }
            ::v-deep .el-form-item {
              width: 160px;
              height: 48px;
            }
          }
        }
      }
    }
  }
}
</style>
